import pandas as pd
import requests
import json
import numpy as np
from common.database import OLAP
from common.log import log_handler

log = log_handler.LogHandler().get_log()


def request_url_get(url):
    """ 请求url方法get方法 """
    try:
        r = requests.get(url=url, timeout=30)
        if r.status_code == 200:
            return r.text
        return None
    except RequestException:
        log.error('请求url返回错误异常')
        return None


def parse_json(content_json):
    """  解析json函数 """
    result_json = json.loads(content_json)
    return result_json


def request_api(url):
    """ 请求高德api 解析json """
    result = request_url_get(url)
    result_json = parse_json(result)
    return result_json


def run():
    path = "/home/igor/zjlab/data/_province_mapper_.csv"
    dtype = {"zipcode": str}
    df = pd.read_csv(path, dtype=dtype)
    geoms = []
    cities = df['zh_full']
    key = "39da746b37f2f1485d7eddcc410dd91a"

    for city in cities:
        index_url = f"https://restapi.amap.com/v3/config/district?keywords={city}&subdistrict=0&extensions=all&key={key}"
        polyline = request_api(index_url)["districts"][0]["polyline"]
        polylines = polyline.split("|")
        lens = [len(p) for p in polylines]
        polyline = polylines[np.argmax(lens)]

        pts = [p.split(",") for p in polyline.split(";")]
        polyline_df = pd.DataFrame(pts)

        polyline_df = polyline_df[[0, 1]]
        polyline_df = polyline_df.apply(pd.to_numeric)
        polyline_df.columns = ["x", "y"]
        polyline_df["_record_id_"] = range(len(polyline_df))

        OLAP.save_dataframe("dataset.polyline", polyline_df)
        geom = \
            OLAP.execute_query(
                "select ST_MakeLine(st_point(x::float,y::float) order by _record_id_) from dataset.polyline").values[0][
                0]
        geoms.append(geom)
    df["geom"] = geoms
    df.to_csv(path, index=None)
